﻿using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.Messaging;
using FileTransferDesktop.Message;
using FileTransferDesktop.Services;
using Clipboard = System.Windows.Clipboard;
using MessageBox = System.Windows.MessageBox;

namespace FileTransferDesktop.ViewModels.Pages;

public partial class ShareList : ObservableObject
{
    [ObservableProperty]
    private string _fileName = string.Empty;

    [ObservableProperty]
    private string _status = string.Empty;

    [ObservableProperty]
    private string _shareCode = string.Empty;

    [ObservableProperty]
    private string _message = string.Empty;

    [ObservableProperty]
    private DateTime _createdTime = DateTime.Now;
}

public partial class MyShareViewModel : ObservableObject, IRecipient<MyShareChangedMessage>
{
    [ObservableProperty]
    private ObservableCollection<ShareList> _shareList = [];

    public MyShareViewModel()
    {
        LoadShareHistory();
        WeakReferenceMessenger.Default.Register<MyShareChangedMessage>(this);
    }

    public void Receive(MyShareChangedMessage message)
    {
        LoadShareHistory();
    }

    private void LoadShareHistory()
    {
        var records = LocalDbService
            .GetAllUploads()
            .Where(r => r.Status == "已上传")
            .OrderByDescending(r => r.UploadTime);

        ShareList = new ObservableCollection<ShareList>(
            records.Select(r => new ShareList
            {
                FileName = r.FileName,
                Status = r.Status,
                ShareCode = r.ShareCode,
                Message = r.Message,
                CreatedTime = r.UploadTime,
            })
        );
    }

    [RelayCommand]
    private static void CopyCode(string? code)
    {
        if (string.IsNullOrEmpty(code))
            return;
        Clipboard.SetText(code);
        MessageBox.Show($"已复制分享码: {code}", "复制成功");
    }
}
